package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.user.OAAuthenticationException;
import com.ruoyi.common.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    /**
     * 执行过滤器内部逻辑，用于处理用户认证信息
     *
     * @param request  HTTP请求对象，包含客户端请求信息
     * @param response HTTP响应对象，用于向客户端返回数据
     * @param chain    过滤器链，用于继续执行后续过滤器
     * @throws ServletException Servlet异常
     * @throws IOException      IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        try {
            // 从请求中获取登录用户信息
            LoginUser loginUser = tokenService.getLoginUser(request);
            // 如果存在登录用户且当前安全上下文中没有认证信息，则进行认证处理
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                // 验证用户令牌的有效性
                tokenService.verifyToken(loginUser);
                // 构建认证令牌并设置认证信息
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            // 继续执行过滤器链中的下一个过滤器
            chain.doFilter(request, response);
        } catch (OAAuthenticationException e){
            // 直接调用AuthenticationEntryPoint处理OA认证异常
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(500, e.getMessage())));
            // authenticationEntryPoint.commence(request, response, e);
        }  catch (Exception e) {
            // 其他异常转换为Spring Security异常
            AuthenticationException authException = new BadCredentialsException("认证失败", e);
            authenticationEntryPoint.commence(request, response, authException);
        }
    }

}
